package comm.util;

import com.fasterxml.jackson.core.type.TypeReference;
import comm.TokenContext;
import comm.util.JsonUtils;
import model.PageResult;
import model.Result;
import model.activity.HdOpenActivityVO;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class HdOpenHttpUtils extends HdOpenUtilBase {

    //缓存 活动url
    private static Map<String, String> activityUrlCacheMap = new HashMap<>();
    private static Lock activityUrlReqLock = new ReentrantLock();


    //通过aid+活动id 获取活动链接，所以调用接口获取到活动链接后缓存即可
    public static String getActivityUrl(int aid, int activityId) throws Exception {
        String cacheKey = "cache:" + aid + ":" + activityId;
        //如果缓存有此活动的 url，则直接从缓存取，可大幅提高响应速度
        if (activityUrlCacheMap.containsKey(cacheKey)) {
            return activityUrlCacheMap.get(cacheKey);
        }
        String activityUrl = "";
        boolean locked = false;
        try {
            locked = activityUrlReqLock.tryLock(2000L, TimeUnit.SECONDS);
            if (!locked) {
                throw new Exception("tryLock wait too long");
            }
            // double check 锁内检查
            if (activityUrlCacheMap.containsKey(cacheKey)) {
                return activityUrlCacheMap.get(cacheKey);
            }
            //获取保存的token，这里取保存的token即可，无需每次请求接口获取
            TokenContext tokenContext = HdOpenHttpUtils.getAccessToken();
            if (tokenContext == null) {
                HdOpenHttpUtils.LOGGER.error("getAccessToken err");
                throw new Exception("getAccessToken err");
            }
            String accessToken = tokenContext.getAccessToken();
            //调用接口获取 活动信息
            Result<HdOpenActivityVO> result = HdOpenHttpUtils.getActivitiesInfo(accessToken, aid, activityId);
            // 获取失败失败
            if (result.getCode() != 0) {
                // 失败告警
                throw new Exception(result.getMsg());
            }
            System.out.println("getActivitiesInfo,code=" + result.getCode());
            HdOpenActivityVO activityInfo = result.getData();
            activityUrl = activityInfo.getActivityUrl();
            //获取成功，放入缓存中
            activityUrlCacheMap.put(cacheKey, activityUrl);
        }finally {
            if (locked) {
                activityUrlReqLock.unlock();
            }
        }
        return activityUrl;
    }



    /**
     * 获取活动列表
     *
     * @Param aid 必须 凡科用户标识
     * @Param activityType 非必须 活动类型（默认全部查询全部-1）
     * @Param sort 非必须 排序（默认id）
     * @Param pageNo 非必须 页数（默认1）
     * @Param pageSize 非必须 返回的最大记录数（默认10）
     * @Author: junes 2022/9/14 19:54
     * @Update: junes 2022/9/14 19:54
     */
    public static PageResult<HdOpenActivityVO> getActivitiesList(String accessToken, int aid, int activityType, String sort, int pageNo, int pageSize) throws Exception {
        String url = API_URL + "/open-api/activities/list-page";
        OkHttpUtils httpUtils = OkHttpUtils.builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + accessToken)
                .addParam("aid", String.valueOf(aid))
                .addParam("activityType", String.valueOf(activityType))
                .addParam("sort", sort)
                .addParam("pageNo", String.valueOf(pageNo))
                .addParam("pageSize", String.valueOf(pageSize));

        String resultJson = httpUtils.get().sync();
        TypeReference typeReference = new TypeReference<PageResult<HdOpenActivityVO>>() {
        };

        return (PageResult<HdOpenActivityVO>) JsonUtils.nativeRead(resultJson, typeReference);
    }

    /**
     * 获取活动详情
     *
     * @Param aid 必须 凡科用户标识
     * @Param activityId 必须 活动id
     * @Author: junes 2022/9/14 19:54
     * @Update: junes 2022/9/14 19:54
     */
    public static Result<HdOpenActivityVO> getActivitiesInfo(String accessToken, int aid, int activityId) {
        String url = API_URL + "/open-api/activities/one";
        OkHttpUtils httpUtils = OkHttpUtils.builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + accessToken)
                .addParam("aid", String.valueOf(aid))
                .addParam("activityId", String.valueOf(activityId));

        String resultJson = httpUtils.get().sync();
        TypeReference typeReference = new TypeReference<Result<HdOpenActivityVO>>() {
        };

        return (Result<HdOpenActivityVO>) JsonUtils.nativeRead(resultJson, typeReference);
    }

    /**
     * 拼接活动地址
     *
     * @Author: junes 2022/9/16 17:44
     * @Update: junes 2022/9/16 17:44
     */
    public static String jointActivityUrl(String accessToken, String url) {
        return url + "&partner_access_token=" + accessToken;
    }

}
